package com.norteksoft.projectname.module1.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.norteksoft.projectname.module1.dao.PersonDao;
import com.norteksoft.projectname.module1.model.Person;
import com.norteksoft.struts.dao.HibernateEntityDao;

/**
 * @spring.bean id="personDao"
 * @spring.property name="sessionFactory" ref="sessionFactory"
 * @spring.property name="entityClass"
 *                  value="com.norteksoft.projectname.module1.model.Person"
 * @author huhc
 * 
 */
public class PersonDaoImpl extends HibernateEntityDao implements PersonDao {
	private static Log log = LogFactory.getLog(PersonDaoImpl.class);

	public void update(Person person, boolean newFile, final Long attachmentId) {
		/*
		 * 无法在一个事务中完成更新和删除
		 * 对于update和delete语句Hibernate对sql语句的执行顺序不一定和书写的顺序一致
		 */
		//
		// TODO Auto-generated method stub
		// 避免更新附件信息时从数据库中读取blob字段
		log.debug("************person.id:" + person.getId());
		log.debug("************attachment-id:" + attachmentId);
		log.debug("************photoName:"+person.getPhotoName());
		person.setPhotoName("afsafddd");
		log.debug("************photoName:"+person.getPhotoName());
		getHibernateTemplate().update(person);
		// 删除掉旧文件
		if (newFile) {
			
		}

	}

	public Long getAttachmentId(Long personId) {
		// TODO Auto-generated method stub
		List result = getHibernateTemplate()
				.find(
						"select person.attachment.id from Person person where person.id=?",
						personId);
		return (Long) result.get(0);
	}
	
	public void deleteAttachment(final Long id){
		getHibernateTemplate().execute(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				session.createSQLQuery("delete from Attachment a where a.id=?")
						.setLong(0, id.longValue())
						.executeUpdate();
				return null;
			}

		});
	}

	public Person getPerson(String name) {
		// TODO Auto-generated method stub
		List persons=getHibernateTemplate().find("from Person where name=?",name);
		return persons.size()>0?(Person)persons.get(0):null;
	}
}
